package cn.edu.nbpt.campus_api.service.blog.impl;

import cn.edu.nbpt.campus_api.exception.BizException;
import cn.edu.nbpt.campus_api.mapper.blog.ArticleMapper;
import cn.edu.nbpt.campus_api.model.ErrorCode;
import cn.edu.nbpt.campus_api.model.Page;
import cn.edu.nbpt.campus_api.model.blog.entity.Article;
import cn.edu.nbpt.campus_api.model.campus.entity.Clazz;
import cn.edu.nbpt.campus_api.service.blog.ArticleService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public Page<Article> selectArticleList(String title, Integer state, String author, Integer categoryId, LocalDate publishStartTime, LocalDate publishEndTime, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articles = articleMapper.selectArticleList(title, state, author, categoryId, publishStartTime, publishEndTime);
        return Page.page(articles);
    }

    @Override
    public Article selectArticle(Integer id) {
        Article article = articleMapper.selectArticle(id);
        if (article == null) throw new BizException(ErrorCode.SELECT_ERROR);
        return article;
    }

    @Override
    public Integer insertArticle(Article article) {
        article.setCreateBy("admin");
        article.setCreateTime(new Date());
        Integer row = articleMapper.insertArticle(article);
        if (row == 0) throw new BizException(ErrorCode.INSERT_ERROR);
        return article.getId();
    }

    @Override
    public Integer updateArticle(Article article) {
        article.setUpdateBy("user");
        article.setUpdateTime(new Date());
        Integer row = articleMapper.updateArticle(article);
        if (row == 0) throw new BizException(ErrorCode.UPDATE_ERROR);
        return article.getId();
    }

    @Override
    public Integer deleteArticle(List<Integer> ids) {
        Integer row = articleMapper.deleteArticle(ids);
        if (row == 0) throw new BizException(ErrorCode.DELETE_ERROR);
        return row;
    }
}
